package demo.server.socket;

import java.io.InputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import core.server.ServerHandler;
import demo.server.model.QueueModel;

public class DemoHandler extends ServerHandler<String>{
	
	private QueueModel que;
	private InputStream is = null;
	private Logger logI = LoggerFactory.getLogger("LogInfo");
	private Logger logE = LoggerFactory.getLogger("LogError");
	private String clientName = null;

	public DemoHandler(Socket clientSocket) {
		super(clientSocket);
	}
	
	public DemoHandler(Socket clientSocket, QueueModel que){
		super(clientSocket);
		this.que = que;
	}


	@Override
	public byte[] encode(Object t) {
		return null;
	}

	@Override
	public String decode() {
		if (is == null) {
			is = getInputStream();
		}
		byte[] bt = read(is, 4);
		int leng = ByteBuffer.wrap(bt).getInt();
		if(leng == 0){
			return null;
		}
		logI.debug("{Server} <<< Received| Length " +  leng);
		
		bt = read(is, 20);
		String info = "";
		if(bt != null){
			info = new String(bt);
			info = info.trim();
			if (clientName == null) {
				clientName = info;
			}
		}
		
		logI.debug("{Server} <<< Received| Info");
		
		logI.debug("{Server} <<< Received| read byte:");
		bt = read(is, 3125);
		if(bt != null){
			leng = bt.length;
			String data = new String(bt);
			logI.info("{Server} <<< Received| IdMessage: " + info + " | Size: " + leng);
			bt = null;
			return data;
			
		}
		bt = null;
		return null;
	}
	
	@Override
	public void onReceive(String t) {
		if (t.length() == 0) {
			return;
		}
//		que.addLast(t);
		logI.info("SizeQueue: " + que.size());
		synchronized (que) {
			que.notifyAll();
		}
	}

	@Override
	public void onConfig() {
		
	}

	@Override
	public void onError(Exception e, String errorType) {
		if (e instanceof SocketException) {
			stopReceive();
			closeSocket();
			return;
		}
		e.printStackTrace();
		logE.error("", e);
	}

	@Override
	public void onIdle() {
		if (clientName != null) {
			logI.info("Server >>> " + clientName + " time idle" );
		}
		
	}

	@Override
	public void onRun() {
		
	}


}
